package com.sky.module.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.module.system.permission.domain.entity.Permission;
import com.sky.module.system.permission.service.PermissionService;
import com.sky.module.system.user.dao.UserMapper;
import com.sky.module.system.user.domain.entity.User;
import com.sky.module.system.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/***
 * @description 用户认证处理器类
 * @param null
 * @return
 * @date 2023/2/20 9:55
 *
 */

@Component
public class CustomUseDetailService implements UserDetailsService {
    @Resource
    private UserService userService;

    @Resource
    private PermissionService permissionService;

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        final User user = userMapper.selectOne(wrapper);
//        final User user = userService.findUserByUserName1(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名错误");
        }
//        查询当前登录用户的权限列表
        final List<Permission> permissionList = permissionService.findPermissionListByUserId(user.getId());
//        转换得到code 权限编码
        List<String> codeList = permissionList.stream().filter(Objects::nonNull)
                .map(item -> item.getCode()).filter(Objects::nonNull)
                .collect(Collectors.toList());
        String[] Authorities = codeList.toArray(new String[codeList.size()]);
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(Authorities);
//         设置菜单列表
        user.setAuthorities(authorityList);
        user.setPermissionList(permissionList);
        return user;
    }

    public static void main(String[] args) {

    }
}
